﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Koolwired.Imap;
using Koolwired.Imap.ForDummies;
using KoolwiredClientApp.Properties;
using System.Threading;

namespace KoolwiredClientApp
{
    public partial class KoolwiredClientForm : Form
    {
        Mailbox mailbox;
        bool bwBusy = false;
        BackgroundWorker bwGetMessageDetails = new BackgroundWorker();

        public KoolwiredClientForm()
        {
            InitializeComponent();
            bwGetMessageDetails.DoWork += new DoWorkEventHandler(bwGetMessageDetails_DoWork);
            bwGetMessageDetails.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwGetMessageDetails_RunWorkerCompleted);
        }

        void bwGetMessageDetails_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (dataGridViewMessages.SelectedRows.Count.Equals(1))
            {
                if (dataGridViewMessages.SelectedRows[0].Index < mailbox.Messages.Count)
                {
                    try
                    {
                        textBoxBody.Text = mailbox.Messages[dataGridViewMessages.SelectedRows[0].Index].GetPlainBodyText();
                        dataGridViewAttachments.DataSource = mailbox.Messages[dataGridViewMessages.SelectedRows[0].Index].Attachments;
                    }
                    catch (Exception exp)
                    {
                        //in case there is a problem (mostly malformed bodypart), just write the error message in the textBoxBody
                        textBoxBody.Text = String.Format("ERROR:\r\n{0}\r\n{1}",exp.Message,exp.StackTrace);
                    }
                }
            }
            bwBusy = false;
        }

        void bwGetMessageDetails_DoWork(object sender, DoWorkEventArgs e)
        {
            bwBusy = true;
        }

        private void SaveAttachment()
        {
            if (dataGridViewMessages.SelectedRows.Count > 0 && mailbox.Messages[dataGridViewMessages.SelectedRows[0].Index].Attachments.Count > 0)
            {
                mailbox.Messages[dataGridViewMessages.SelectedRows[0].Index].Attachments[dataGridViewAttachments.SelectedRows[0].Index].Save(textBoxAttachmentPath.Text);
            }
        }

        private void SaveAllAttachments()
        {
            if (dataGridViewMessages.SelectedRows.Count > 0) mailbox.Messages[dataGridViewMessages.SelectedRows[0].Index].SaveAttachments(textBoxAttachmentPath.Text);
        }

        private void KoolwiredClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (mailbox != null) mailbox.Close();
        }

        private void GetMessages()
        {
            if (mailbox != null) mailbox.Close();
            mailbox = new Mailbox(textBoxServer.Text, textBoxUsername.Text, textBoxPassword.Text);
            mailbox.MessagesPerPage = 25;
            toolStripComboBoxFolders.Items.Clear();
            toolStripComboBoxFolders.SelectedText = "";
            foreach (string folder in mailbox.AllFolders)
            {
                int index = toolStripComboBoxFolders.Items.Add(folder);
                if (folder.Equals(mailbox.CurrentFolder))
                {
                    toolStripComboBoxFolders.SelectedIndex = index;
                }
            }
            UpdateMessageControls();
        }

        private void UpdateMessageControls()
        {
            textBoxBody.Text = "";
            dataGridViewAttachments.DataSource = null;
            toolStripStatusLabelMessageCount.Text = String.Format("# message(s): {0}", mailbox.MessageCount);
            dataGridViewMessages.DataSource = mailbox.Messages;
            toolStripComboBoxPage.Items.Clear();
            for (var i = 1; i <= mailbox.PageCount; i++)
            {
                toolStripComboBoxPage.Items.Add(i);
            }
            toolStripComboBoxPage.SelectedIndex = mailbox.Page;
        }

        private void DeleteSelectedMessage()
        {
            if (dataGridViewMessages.SelectedRows.Count > 0)
            {
                mailbox.Messages[dataGridViewMessages.SelectedRows[0].Index].Delete();
                UpdateMessageControls();
                if (dataGridViewMessages.Rows.Count > 0)
                {
                    dataGridViewMessages.Rows[0].Selected = true;
                }
            }
        } 

        private void ChangeCurrentFolder()
        {
            if (!toolStripComboBoxFolders.SelectedItem.ToString().Equals(mailbox.CurrentFolder))
            {
                mailbox.CurrentFolder = toolStripComboBoxFolders.SelectedItem.ToString();
                UpdateMessageControls();
            }
        }


        private void ChangePage()
        {
            if (!toolStripComboBoxPage.SelectedIndex.Equals(mailbox.Page))
            {
                mailbox.Page = toolStripComboBoxPage.SelectedIndex;
                UpdateMessageControls();
            }
        }
        
        #region Form events

        private void KoolwiredClientForm_Load(object sender, EventArgs e)
        {
            textBoxServer.Text = Settings.Default.Mailserver;
            textBoxUsername.Text = Settings.Default.Username;
            textBoxPassword.Text = Settings.Default.Password;
            textBoxAttachmentPath.Text = Settings.Default.Attachmentspath;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            GetMessages();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            DeleteSelectedMessage();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            SaveAllAttachments();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            SaveAttachment();
        }

        private void dataGridViewMessages_SelectionChanged(object sender, EventArgs e)
        {
            if (!bwBusy && !bwGetMessageDetails.IsBusy)
            {
                try
                {
                    bwGetMessageDetails.RunWorkerAsync();
                }
                catch { }
            }
        }

        private void toolStripComboBoxFolders_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeCurrentFolder();
        }


        private void toolStripComboBoxPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangePage();
        }

        #endregion Form events

    }
}
